<template>
  <div class="outsourcing">
    <el-card>
      <div class="outsourcing-search">
        <el-form ref="form" :inline="true" label-width="130px" :model="form">
          <el-form-item label="外购件名称池:：">
            <el-input v-model="form.OUT_SOURCE_POOL_NAME" />
          </el-form-item>
          <el-form-item label="外购设备名称：">
            <el-input v-model="form.OUT_SOURCE_EQUIPMENT_NAME" />
          </el-form-item>
          <el-form-item>
            <el-button @click="reset">
              <vui-icon icon="refresh-line" />
              重置
            </el-button>
            <el-button type="primary" @click="query">
              <vui-icon icon="search-line" />
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card>
      <div style="display: flex">
        <el-button style="margin-right: 20px" type="primary" @click="equipmentAdd">
          <vui-icon icon="add-line" />
          新增设备池
        </el-button>
        <el-button type="warning" @click="toLead">
          <vui-icon icon="upload-line" />
          导入数据
        </el-button>
      </div>
      <div class="table-content">
        <el-table border :data="list" highlight-current-row>
          <el-table-column label="ID" prop="ID" width="100" />
          <el-table-column label="外购件名称池" prop="OUT_SOURCE_POOL_NAME" />
          <el-table-column label="外购设备名称" prop="OUT_SOURCE_EQUIPMENT_NAME" />
          <el-table-column label="自定义1" prop="UDF1" />
          <el-table-column label="创建人员" prop="ADDWHO" />
          <el-table-column label="创建时间" prop="ADDTIME" />
          <el-table-column label="修改人员" prop="EDITWHO" />
          <el-table-column label="修改时间" prop="EDITTIME" />
          <el-table-column fixed="right" label="操作" width="130">
            <template #default="{ row }">
              <el-button type="text" @click="editor(row)">
                <vui-icon icon="edit-line" />
                编辑
              </el-button>
              <el-button type="text" @click="dele(row)">
                <vui-icon icon="close-circle-line" />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :page-size="size"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog v-model="visible" :title="title" width="50%" @close="close">
      <div>
        <p class="hint_">基础信息</p>
        <el-form class="demo-form-inline" :inline="true" label-position="top" :model="subForm">
          <el-form-item label="外购件名称池" required>
            <el-input v-model="subForm.OUT_SOURCE_POOL_NAME" :disabled="isEditor" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>
      <div class="title">
        <p class="hint_">明细设备</p>
        <p v-if="!isEditor">每行完成编辑后，回车自动生成下一行</p>
      </div>
      <el-table border :data="tableData" max-height="250" style="width: 100%">
        <el-table-column fixed label="ID" prop="ID" width="80" />
        <el-table-column fixed label="设备名称">
          <template #default="{ row, $index }">
            <el-input
              :ref="'input' + $index"
              v-model="row.OUT_SOURCE_EQUIPMENT_NAME"
              placeholder="请输入"
              @keyup.enter="addByEnterKey(row, $index)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="footer_">
        <el-button v-if="!isEditor" @click="resetVisible">重置</el-button>
        <el-button type="primary" @click="submitVisibleForm">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="uploadVisible" title="外购设备池上传" width="80%" @close="cancel">
      <div v-if="uploadVisible">
        <el-steps :active="active" align-center>
          <el-step title="上传模版数据" />
          <el-step title="模版数据检测" />
          <el-step title="单据建立完成" />
        </el-steps>
        <div class="step-two">
          <div v-if="active == 1">
            <div class="hint_">
              <p class="hint-title">特别提示</p>
              <p class="hint-explain">请使用系统要求模板按格式要求填写数据，填写完成进行数据上传</p>
            </div>
            <div class="box_">
              <div class="left-box"></div>
              <div>
                <p>填写导入数据信息</p>
                <p>请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除</p>
                <el-button type="text" @click="download">下载模板</el-button>
              </div>
            </div>
            <div class="box_">
              <div class="left-box"></div>
              <vui-upload
                ref="fileUploadRef"
                class="text-left"
                :file-name="uploadOptions.name"
                :limit="1"
                :post-data="uploadOptions.postData"
                :url="uploadOptions.url"
                @uploadSuccess="uploadSuccess"
              >
                <div>
                  <p>上传填好的信息表</p>
                  <p>文件后缀名必须为xls或xlsx(既Excel格式)，文件大小不得大于10M</p>
                  <el-button v-if="!file" size="small" type="text">上传文件</el-button>
                </div>
              </vui-upload>
            </div>
            <div class="footer_">
              <el-button type="primary" @click="clickUpload">下一步</el-button>
            </div>
          </div>
          <div v-if="active == 2">
            <div v-if="abnormal">
              <div class="box_" style="height: 80px">
                <div class="left-box"></div>
                <div>
                  <p>正常数量条数：{{ errorData.successNumber }}</p>
                  <p>
                    异常数量条数：
                    <span style="color: red">{{ errorData.failNumber }}</span>
                  </p>
                </div>
              </div>
              <div class="abnormal-hint">
                <p>异常提示</p>
                <template v-for="(item, index) in errorData.errorInfoList" :key="index">
                  <p style="color: red">
                    {{ item }}
                  </p>
                </template>
              </div>
            </div>
          </div>
          <div v-if="active == 3">
            <div>
              <p>数据导入成功</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import requestMethod from '../../common/requestMethod'
  import publicFn from '../../common/requestCommon'
  import { GFCD } from '@/utils/utils'
  import { download } from '../../api/home'
  const configSetting = GFCD('bqms')
  // import publicFn from '../common/requestCommon'
  export default {
    name: 'Outsourcing',
    data() {
      return {
        active: 1,
        uploadOptions: {
          postData: {
            method: requestMethod.OUTSOURCING_IMPORT,
            data: '{"TEMP_TYPE":"OUT_POOL_SOURCE"}',
          },
          name: 'uploadFile',
          url: `${configSetting.domain}${configSetting.baseUrl}`,
        },
        uploadVisible: false,
        visible: false,
        form: {},
        list: [],
        size: 10,
        total: 0,
        currentPage: 1,
        title: '新增外购件名称池',
        subForm: {},
        tableData: [{ ID: '', OUT_SOURCE_EQUIPMENT_NAME: '' }],
        isEditor: false,
        formEnd: {},
        abnormal: false,
        errorData: {},
      }
    },
    methods: {
      equipmentAdd() {
        this.subForm.OUT_SOURCE_POOL_NAME = ''
        this.tableData = [{ ID: '', OUT_SOURCE_EQUIPMENT_NAME: '' }]
        this.visible = true
      },
      clickUpload() {
        if (this.$refs['fileUploadRef'].allImgNum) {
          this.$refs['fileUploadRef'].submitUpload()
        } else {
          this.$message({
            type: 'error',
            message: '请选择文件',
          })
        }
      },
      cancel() {
        this.getOutsourcing()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.query()
      },
      addByEnterKey(row, index) {
        if (!row.OUT_SOURCE_EQUIPMENT_NAME) return this.$message.error('请输入明细设备')
        if (this.isEditor) return
        this.tableData.push({ ID: '', OUT_SOURCE_EQUIPMENT_NAME: '' })
        if (this.$refs['input' + index]) {
          this.$nextTick(() => {
            this.$refs['input' + (index + 1)].focus()
          })
        }
      },
      async download() {
        let res = await download(`${configSetting.domain}${configSetting.baseUrl}`, {
          method: requestMethod.TEMPLATE_DOWNLOAD,
          data: JSON.stringify({ TEMP_TYPE: 'OUT_POOL_SOURCE' }),
        })
        let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        let reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = '外购设备池模板.xlsx'
          a.href = e.target.result
          a.click()
        }
      },
      resetVisible() {
        this.subForm = {}
        this.tableData = [{ ID: '', OUT_SOURCE_EQUIPMENT_NAME: '' }]
      },
      reset() {
        this.form = {}
        this.getOutsourcing()
      },
      close() {
        this.isEditor = false
      },
      async submitVisibleForm() {
        if (!this.subForm.OUT_SOURCE_POOL_NAME) return this.$message.error('请输入外购件名称池')
        let list = []
        let method = ''
        if (this.isEditor) {
          if (!this.tableData[0].OUT_SOURCE_EQUIPMENT_NAME) return this.$message.error('请输入外购件设备名称')
          list = [{ OUT_SOURCE_POOL_NAME: this.subForm.OUT_SOURCE_POOL_NAME, ...this.tableData[0] }]
          method = requestMethod.OUTSOURCING_EDIT
        } else {
          method = requestMethod.OUTSOURCING_ADD
          this.tableData.forEach((row) => {
            if (row.OUT_SOURCE_EQUIPMENT_NAME) {
              list.push({ OUT_SOURCE_POOL_NAME: this.subForm.OUT_SOURCE_POOL_NAME, OUT_SOURCE_EQUIPMENT_NAME: row.OUT_SOURCE_EQUIPMENT_NAME })
            }
          })
        }
        if (list.length == 0) return this.$message.error('请输入外购件设备名称')
        let res = await publicFn(method, list)
        if (res.code === '00000') {
          let hint = '新增'
          if (this.isEditor) hint = '编辑'
          this.$message({
            type: 'success',
            message: hint + '成功',
          })
          this.visible = false
          this.isEditor = false
          this.getOutsourcing()
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      query() {
        // this.currentPage = 1
        this.getOutsourcing()
      },
      async getOutsourcing() {
        let res = await publicFn(requestMethod.OUTSOURCING_QUERY, { ...this.form, '#LIMIT#': this.currentPage, '#PAGE_SIZE#': this.size })
        if (res.code === '00000') {
          this.total = res.data[requestMethod.OUTSOURCING_QUERY].count
          this.list = res.data[requestMethod.OUTSOURCING_QUERY].data
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      async threeNext() {
        let res = await publicFn(requestMethod.OUTSOURCING_RECORD, this.formEnd)
        if (res.code === '00000') {
          this.active++
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      uploadSuccess(file) {
        let res = file.fileList[0].response
        console.log(res)
        if (res.code === '00000') {
          this.formEnd.FILE_PATH = res.data.filePath
          this.formEnd.FILE_NAME = res.data.fileName
          this.formEnd.FILE_HIS_NAME = res.data.originalFileName
          this.active++
          this.abnormal = false
          this.threeNext()
        } else if (res.code === 'S0055') {
          this.errorData.successNumber = res.count
          this.errorData.failNumber = res.data.length
          this.errorData.errorInfoList = res.data
          this.$message({
            type: 'error',
            message: res.msg,
          })
          this.abnormal = true
          this.active++
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
          })
        }
      },
      editor(row) {
        console.log(row)
        this.subForm.OUT_SOURCE_POOL_NAME = row.OUT_SOURCE_POOL_NAME
        this.tableData = [{ ID: row.ID, OUT_SOURCE_EQUIPMENT_NAME: row.OUT_SOURCE_EQUIPMENT_NAME }]
        this.title = '编辑外购件名称池'
        this.isEditor = true
        this.visible = true
      },
      dele(row) {
        console.log(row)
        this.$confirm('此操作将删除该品牌, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await publicFn(requestMethod.OUTSOURCING_DEL, { ID: row.ID })
            if (res.code === '00000') {
              this.$message({
                type: 'success',
                message: '删除成功',
              })
              this.getOutsourcing()
            } else {
              this.$message({
                type: 'info',
                message: res.msg,
              })
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      toLead() {
        this.active = 1
        this.errorData = {}
        this.uploadVisible = true
      },
    },
  }
</script>
<style lang="scss" scoped>
  @import '../../static/scss/Dialog.scss';
  .outsourcing {
    padding: 15px;
    .table-content {
      margin-top: 20px;
    }
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .footer_ {
      margin-top: 20px;
      text-align: center;
    }
    .flex_ {
      display: flex;
      justify-content: space-between;
    }
    .el-select .el-input .el-input__inner {
      width: 193px !important;
    }
    .hint_ {
      background: #fff5e6;
      padding: 15px 30px;
      box-sizing: border-box;
      .hint-title {
        font-weight: 600;
      }
      .hint-explain {
        margin-top: 10px;
      }
    }
    .step-two {
      margin-top: 20px;
    }
    .box_ {
      margin-top: 20px;
      display: flex;
      align-items: center;
      height: 115px;
      border: 1px solid #d8d3d3;
      p {
        margin-top: 10px;
      }
    }
    .left-box {
      background: #f5f5f5;
      width: 50px;
      height: 100%;
    }
    .abnormal-hint {
      padding: 15px;
      margin-top: 20px;
      box-sizing: border-box;
      border: 1px solid #f5f5f5;
      p {
        margin-top: 10px;
      }
    }
    .success {
      display: flex;
      justify-content: center;
      align-items: center;
      & > div {
        height: 300px;
      }
    }
  }
</style>
